import './public-path'
import './register-hook'
import './register-service-worker'
import Vue from 'vue'
import App from './App.vue'
import { Router } from './router'
import store from './store'
import { appName, DEBUG_MODE } from './config'
import plugins from './plugin'
import { QiankunApp } from '@lhy-assist/qiankun'
import { PlatformFrameProps } from 'qiankun-frame'
import { qiankunApp } from './qiankun/qiankun-app'
import * as mutationTypes from '@/store/mutation-type'
import '@/asset/css/style'

Vue.config.productionTip = DEBUG_MODE
Vue.use(plugins)

export class VueApp {
  /**
   * 实例
   *
   * @protected
   * @static
   * @type {(Vue | null)}
   * @memberOf VueApp
   */
  protected static app: Vue | null = null

  /**
   * 渲染实例
   *
   * @static
   * @param {HTMLElement} [container]
   * @param {string} [activeRule]
   *
   * @memberOf VueApp
   */
  public static render(container?: HTMLElement, activeRule?: string) {
    this.app = new Vue({
      router: Router.create(activeRule),
      store,
      render: h => h(App),
    }).$mount(container ? (container.querySelector('#app') as HTMLElement) : '#app')
  }

  /**
   * 销毁
   *
   * @static
   *
   * @memberOf VueApp
   */
  public static destroy() {
    if (this.app) {
      this.app.$destroy()
      this.app.$el.innerHTML = ''
      this.app = null
    }
  }
}

// 非qiankun子应用时独立启动app
if (!QiankunApp.active) {
  VueApp.render()
}

// ************* 暴露钩子函数给qiankun ************* //
export async function bootstrap() {
  console.log(`${appName} bootstrap`)
}
export async function mount(props: PlatformFrameProps) {
  console.log(`${appName} mount`)
  qiankunApp.initFrame(props)
  store.commit(mutationTypes.SET_FRAME_STATE, qiankunApp.state)
  VueApp.render(props.container, props.activeRule)
}
export async function unmount() {
  console.log(`${appName} unmount`)
  VueApp.destroy()
  Router.destroy()
}
